import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/routes/app_routes.dart';
import 'package:seedfour/app/services/common_service.dart';
import 'package:seedfour/app/views/module_case/case_create/logic.dart';
import 'package:seedfour/toolkit/utils/encrypt_utils.dart';

import '../../../models/case_list_entity.dart';
import '../../../models/invoice_entity.dart';
import '../../../services/api_service.dart';
import '../../web_screen/screen_params.dart';

class OrderPaidCreateLogic extends GetxController {
  late GlobalKey<FormState> formKey;

  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  // 付款金额输入框控制器
  late TextEditingController amountController;

  // 银行户名输入框控制器
  late TextEditingController bankAccountNameController;

  // 银行账号输入框控制器
  late TextEditingController bankAccountController;

  // 开户银行名称输入框控制器
  late TextEditingController bankNameController;

  // 备注输入框控制器
  late TextEditingController remarkController;

  // 支付密码输入框控制器
  late TextEditingController payPasswordController;

  var invoiceTotalAmount = '¥0.00'.obs;
  var attachmentNames = [].obs;

  final List<PlatformFile> _paths = [];
  late InvoiceEntity _invoiceEntity;

  final caseList = <CaseInfo?>[].obs;
  final selectedCaseIndies = <int>[].obs;
  final selectedCases = <CaseInfo?>[].obs;

  @override
  void onInit() {
    super.onInit();
    formKey = GlobalKey<FormState>();
    amountController = TextEditingController();
    bankAccountNameController = TextEditingController();
    bankAccountController = TextEditingController();
    bankNameController = TextEditingController();
    remarkController = TextEditingController();
    payPasswordController = TextEditingController();

    _invoiceEntity = InvoiceEntity();
    _invoiceEntity.orderAttachs = [];
    _invoiceEntity.relateCases = [];
    _invoiceEntity.invoiceList = [];

    _getCaseList();
  }

  void initPasswordController() {
    payPasswordController = TextEditingController();
  }

  // 选择文件
  void pickFile() async {
    var files = (await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    ))
        ?.files;

    if (files != null && files.isNotEmpty) {
      _paths.addAll(files);
      attachmentNames.addAll(files.map((e) => e.name).toList());
    }
  }

  // 删除文件
  void deleteFile(int index) {
    _paths.removeAt(index);
    attachmentNames.removeAt(index);
  }

  // 选中案件
  void onSelectedCase(int index) {
    if (selectedCaseIndies.contains(index)) {
      selectedCaseIndies.remove(index);
    } else {
      selectedCaseIndies.add(index);
    }
  }

  void onCreateCase() {
    Get.toNamed(RouteGet.caseCreate, arguments: CaseCreatePageType.create);
  }

  // 确认选中案件
  void onConfirmSelectedCase() {
    selectedCases.clear();
    selectedCases.addAll(selectedCaseIndies.map((index) => caseList[index]));
  }

  // 取消选中案件
  void onCanceledSelectedCase() {
    selectedCaseIndies.clear();
  }

  void toSelectInvoice() {
    String token = commonService.getToken() ?? '';
    String orgId = commonService.getUser().targetSite?.owner ?? '';
    String url =
        'https://www.seedfour.com/clicms/#/findata?orgId=$orgId&token=$token';
    Get.toNamed(RouteGet.webScreen, arguments: WebScreenParams(url: url))!
        .then((value) {
      if (value == null) {
        return;
      }

      printInfo(
          info: '------------------------------------------ 监听财务凭证H5页面返回数据事件');

      Map<String, dynamic> jsonMap = jsonDecode(value[0]);

      List<dynamic> invoiceListJson = jsonMap['invoiceList'];
      List<InvoiceItemEntity> invoiceList = invoiceListJson
          .map((json) => InvoiceItemEntity.fromJson(json))
          .toList();

      _invoiceEntity.invoiceList = invoiceList;

      print('invoiceList: ${_invoiceEntity.invoiceList.toString()}');

      invoiceTotalAmount.value = jsonMap['totalAmount'];
    });
  }

  void submit() async {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();

      EasyLoading.show(status: '正在提交...');
      final result = await _uploadFiles();

      if (!result) {
        EasyLoading.dismiss();
        EasyLoading.showError('文件上传失败');
        return;
      }

      if (commonService.isAssistant()) {
        _createAssistantOrder();
        return;
      }

      var payKey = await apiService.getPayKey();
      if (payKey.isBlank ?? true) {
        EasyLoading.dismiss();
        EasyLoading.showError('获取支付密钥失败');
        return;
      }

      _createOrder(payKey!);
    }
  }

  Future<bool> _uploadFiles() async {
    if (_paths.isEmpty) {
      return true;
    }

    for (var path in _paths) {
      final result = await apiService.uploadFile(path.path!);
      if (result != null) {
        _invoiceEntity.orderAttachs!
            .add(InvoiceOrderAttach(name: result.name, url: result.tempPath));
      } else {
        return false;
      }
    }

    return true;
  }

  void _getCaseList() {
    apiService
        .listAllCase(commonService.getRole(), 'selectCase')
        .then((caseList) {
      if (caseList != null) {
        this.caseList.addAll(caseList.all!);
      }
    });
  }

  void _createAssistantOrder() async {
    _invoiceEntity.relateCases?.addAll(selectedCases
        .map((caseInfo) => InvoiceRelateCases(
              caseId: caseInfo?.id,
              caseName: caseInfo?.caseNameStr,
              time: caseInfo?.caseDate,
            ))
        .toList());

    final result = await apiService.createAssistantPaidOrder(
      action: 'createSubmit',
      amount: amountController.text,
      invoice: _invoiceEntity.toString(),
      mobile: commonService.getUser().mobile ?? '',
      orderType: 6,
      orderRemark: remarkController.text,
      title:
          '${bankAccountNameController.text},${bankAccountController.text},${bankNameController.text}',
    );

    if (result != null) {
      EasyLoading.dismiss();
      EasyLoading.showSuccess('提交成功');
      Get.back(result: true);
    }
  }

  void _createOrder(String key) async {
    String password = rsaEncrypt(key, payPasswordController.text);

    _invoiceEntity.relateCases?.addAll(selectedCases
        .map((caseInfo) => InvoiceRelateCases(
              caseId: caseInfo?.id,
              caseName: caseInfo?.caseNameStr,
              time: caseInfo?.caseDate,
            ))
        .toList());

    final result = await apiService.createPaidOrder(
      amount: amountController.text,
      invoice: _invoiceEntity.toString(),
      mobile: commonService.getUser().mobile ?? '',
      orderType: 6,
      orderRemark: remarkController.text,
      paymentPwd: password,
      title:
          '${bankAccountNameController.text},${bankAccountController.text},${bankNameController.text}',
    );

    if (result != null) {
      EasyLoading.dismiss();
      EasyLoading.showSuccess('提交成功');
      Get.back(result: true);
    }
  }
}
